import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_vant_kit/widgets/addressList.dart';
import 'package:flutter_vant_kit/widgets/dialog.dart';
import 'package:flutter_vant_kit/widgets/divider.dart';
import 'package:flutter_vant_kit/widgets/price.dart';
import 'package:shoes_shop/api/api.dart';
import 'package:shoes_shop/core/const.dart';
import 'package:shoes_shop/core/utils.dart';
import 'package:shoes_shop/models/cart_model.dart';
import 'dart:math' as math;

import 'package:shoes_shop/models/public_provider_model.dart';
import 'package:provider/provider.dart';

import 'login/login_page.dart';
import 'order/order_ detail.dart';
import 'userInfo/addressList/address_list_provider.dart';

class CartPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    String openid = Provider.of<PublicProviderModel>(context, listen: true)
        .userInfo['openid'];
    List<CartModelData> _list =
        Provider.of<PublicProviderModel>(context, listen: true).cartList;
    return Scaffold(
      body: SafeArea(
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 40.w),
          child: Column(
            children: [
              Padding(
                padding: EdgeInsets.symmetric(vertical: 15.w),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      "购物车",
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 32,
                      ),
                    ),
                  ],
                ),
              ),
              Expanded(
                child: openid == null
                    ? Center(
                        child: Container(
                          child: Column(
                            mainAxisSize: MainAxisSize.min, // 自适应高度
                            children: [
                              Text('还未登录'),
                              SizedBox(
                                height: 20.w,
                              ),
                              InkWell(
                                onTap: () {
                                  // 去登录页面
                                  Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                      builder: (context) => LoginPage(),
                                    ),
                                  );
                                },
                                child: Container(
                                  decoration: BoxDecoration(
                                    color: Colors.blue,
                                    borderRadius: BorderRadius.all(
                                      Radius.circular(10.w),
                                    ),
                                  ),
                                  padding: EdgeInsets.symmetric(
                                      horizontal: 50.w, vertical: 20.w),
                                  child: Text(
                                    '去登录',
                                    style: TextStyle(color: Colors.white),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      )
                    : _list.length==0?Center(
                        child: Container(
                          child: Column(
                            mainAxisSize: MainAxisSize.min, // 自适应高度
                            children: [
                              Text('没有商品，请先选购商品',style: TextStyle(color: Colors.black54),),
                            ],
                          ),
                        ),
                      ): ListView.builder(
                        itemCount: _list.length + 1,
                        itemBuilder: (context, index) {
                          if (index == _list.length) {
                            return Padding(
                              padding: EdgeInsets.only(bottom: 30.w),
                              child: NDivider(
                                content: "没有更多了",
                              ),
                            );
                          } else {
                            return _item(_list[index], index, context);
                          }
                        },
                        physics: BouncingScrollPhysics(),
                      ),
                // child: ListView(
                //   children: [
                //     ...context
                //         .watch<PublicProviderModel>()
                //         .cartList
                //         .asMap()
                //         .entries
                //         .map((e) {
                //           print('循环$e');
                //       return _item(e.value, e.key, context);
                //     })
                //   ],
                //   physics: BouncingScrollPhysics(),
                // ),
              ),
              openid == null?Container(): Container(
                height: 80.w,
                width: 650.w,
                decoration: BoxDecoration(
                  color: AppColors.deepBlue,
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(10.w),
                    topRight: Radius.circular(10.w),
                  ),
                ),
                child: Padding(
                  padding: EdgeInsets.all(15.w),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      // Text(
                      //   '全选',
                      //   style: TextStyle(color: Colors.white, fontSize: 28.w),
                      // ),
                      InkWell(
                        onTap: () {
                          showDialog(
                            context: context,
                            builder: (_) {
                              return NDialog(
                                title: '提示',
                                message: '确认清空购物车？',
                                showCancelButton: true,
                                onConfirm: () {
                                  Map res = emptyCart(context);
                                  showToast(res['message']);
                                },
                              );
                            },
                          );
                        },
                        child: Container(
                          width: 100.w,
                          height: 50.w,
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.all(
                              Radius.circular(10.w),
                            ),
                          ),
                          child: Center(
                            child: Text(
                              '清空',
                              style: TextStyle(
                                color: Colors.red,
                              ),
                            ),
                          ),
                        ),
                      ),
                      Expanded(
                        flex: 1,
                        child: Row(
                          children: [
                            Text(
                              '总价：',
                              style: TextStyle(color: Colors.white),
                            ),
                            Price(
                              value: Provider.of<PublicProviderModel>(context,
                                      listen: false)
                                  .cartTotal,
                              color: Colors.white,
                            ),
                            SizedBox(
                              width: 10.w,
                            )
                          ],
                          mainAxisAlignment: MainAxisAlignment.end,
                        ),
                      ),
                      InkWell(
                        onTap: () async {
                          Map<String, dynamic> res = await settlement(context);
                          if (res['code'] == 200) {
                            AddressInfo data = new AddressInfo.fromJson(
                                res['data']['address'][0]);
                            if (res['data']['address'].length > 0) {
                              Provider.of<AddressListProvider>(context,
                                      listen: false)
                                  .changeAddress(data);
                            }
                            Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) => OrderDetail(
                                      goodsList: res['data']['goods_list'],
                                      orderId: res['data']['order_id']),
                                ));
                          } else {
                            showToast(res['message']);
                          }
                        },
                        child: Container(
                          height: 50.w,
                          padding: EdgeInsets.symmetric(horizontal: 20.w),
                          child: Center(
                            child: Settlement(),
                          ),
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.all(
                              Radius.circular(10.w),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

// 结算按钮文字
class Settlement extends StatelessWidget {
  const Settlement({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    String _text = '结算';
    int cartTotalNum =
        Provider.of<PublicProviderModel>(context, listen: false).cartTotalNum;
    if (cartTotalNum <= 0) {
      _text = '结算';
    } else if (cartTotalNum > 99) {
      _text = '(99+) 结算';
    } else {
      _text = '($cartTotalNum) 结算';
    }
    return Text(
      _text,
      style: TextStyle(color: AppColors.deepBlue, height: 1.25),
    );
  }
}

Widget _item(CartModelData item, int index, BuildContext context) {
  return Dismissible(
    key: ValueKey('key'),
    confirmDismiss: (direction) async {
      // 左右滑动删除商品
      Map res = await removeCartGoods(item.sId, index, context);
      if (res['code'] == 200) {
        showToast(res['message']);
        return true;
      } else {
        showToast(res['message']);
        return false;
      }
    },
    child: Container(
      margin: EdgeInsets.only(bottom: 30.w),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(40.w),
        boxShadow: [
          BoxShadow(
              color: Colors.black12,
              offset: Offset(0.0, 15.w), //阴影xy轴偏移量
              blurRadius: 15.w, //阴影模糊程度
              spreadRadius: 0 //阴影扩散程度
              ),
        ],
        color: Colors.white,
      ),
      width: double.infinity,
      height: 250.w,
      child: ClipRRect(
        borderRadius: BorderRadius.circular(40.w),
        child: Row(
          children: [
            Padding(
              padding: EdgeInsets.all(20.w),
              child: Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(
                    Radius.circular(40.w),
                  ),
                  color: AppColors.fadeGrayColor,
                ),
                width: 210.w,
                height: 210.w,
                child: Transform.rotate(
                  angle: -math.pi / 7,
                  origin: Offset(-30.w, 30.w),
                  child: Padding(
                    padding: EdgeInsets.all(10.w),
                    child: Image.network(item.shoesInfo[0].imgs[0]),
                  ),
                ),
              ),
            ),
            SizedBox(
              width: 30.w,
            ),
            Expanded(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '${item.shoesInfo[0].title}',
                    style:
                        TextStyle(fontSize: 35.w, fontWeight: FontWeight.bold),
                  ),
                  SizedBox(
                    height: 20.w,
                  ),
                  Price(value: item.shoesInfo[0].price),
                  SizedBox(height: 20.w),
                  //步进器
                  Row(
                    children: [
                      InkWell(
                        child: Container(
                          width: 60.w,
                          height: 60.w,
                          decoration: BoxDecoration(
                            color: AppColors.grayColor,
                            shape: BoxShape.circle,
                          ),
                          child: Center(
                            child: Text(
                              '-',
                              style: TextStyle(
                                fontSize: 45.w,
                                color: Colors.white,
                              ),
                            ),
                          ),
                        ),
                        onTap: () {
                          int count = item.count - 1;
                          if (count == 0) {
                            removeCartGoods(item.sId, index, context);
                          } else {
                            changeCartGoodsNum(item.sId, count, index, context);
                          }
                        },
                      ),
                      Padding(
                        padding: EdgeInsets.symmetric(horizontal: 10.w),
                        child: Text(
                          countFilter(item.count),
                          style: TextStyle(fontSize: 30.w),
                        ),
                      ),
                      InkWell(
                        child: Container(
                          width: 60.w,
                          height: 60.w,
                          decoration: BoxDecoration(
                            color: AppColors.fadeBlueColor,
                            shape: BoxShape.circle,
                          ),
                          child: Center(
                            child: Text(
                              '+',
                              style: TextStyle(
                                  fontSize: 45.w, color: Colors.white),
                            ),
                          ),
                        ),
                        onTap: () {
                          int count = item.count + 1;
                          changeCartGoodsNum(item.sId, count, index, context);
                        },
                      ),
                    ],
                  )
                ],
              ),
            ),
            // Container(
            //   width: 150.w,
            //   height: double.infinity,
            //   decoration: BoxDecoration(color: Colors.red[100]),
            //   child: Center(
            //     child: Icon(
            //       Icons.delete,
            //       size: 50.w,
            //       color: Colors.red,
            //     ),
            //   ),
            // ),
          ],
        ),
      ),
    ),
  );
}
